<?php

namespace App\Http\Controllers\Blog;

use App\Models\Post;
use App\Models\Tag;

class BlogController extends Controller
{
    /**
     * 首页页面
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $archives = Post::groupByYears()->get();
        $tags = Tag::display()->get();
        $posts = Post::newest()->paginate();

        foreach ($archives as &$archive) {
            $archive->publish_years = $archive->publish_year . '-' . fill_zero($archive->publish_month);
        }

        return view('blog.index', compact('archives', 'tags', 'posts'));
    }

    /**
     * 标签页面
     *
     * @param  string $active_tag
     * @return \Illuminate\View\View
     */
    public function tags($active_tag = '')
    {
        $tags = Tag::display()->get();

        if (! empty($active_tag)) {
            $query = Post::whereHas('tags', function ($sub_query) use ($active_tag) {
                $sub_query->where('name', $active_tag);
            });
        } else {
            $query = Post::query();
        }

        $posts = $query->newest()->paginate();

        return view('blog.tags', compact('tags', 'active_tag', 'posts'));
    }

    /**
     * 归档页面
     *
     * @return \Illuminate\View\View
     */
    public function archives()
    {
        $archives = Post::groupByYears()->get();
        $posts = Post::get();

        foreach ($archives as &$archive) {

            $archive_posts = [];
            $archive_start_years = strtotime("{$archive->publish_year}-{$archive->publish_month}");
            $archive_end_years = strtotime('first day of +1 month', $archive_start_years);

            foreach ($posts as $post) {

                $post_publish_date = strtotime($post->publish_date);

                if ($post_publish_date >= $archive_start_years && $post_publish_date < $archive_end_years) {
                    $archive_posts[] = $post;
                }
            }

            $archive->posts = $archive_posts;
            $archive->publish_years = $archive->publish_year . '-' . fill_zero($archive->publish_month);
        }

        return view('blog.archives', compact('archives'));
    }

    /**
     * 文章详情页面
     *
     * @param  string $slug
     * @return \Illuminate\View\View
     */
    public function detail($slug)
    {
        $post = Post::with('tags')->where('slug', $slug)->firstOrFail();
        $previous_post = Post::newest()->where('id', '>', $post->id)->first();
        $next_post = Post::newest()->where('id', '<', $post->id)->first();

        return view('blog.detail', compact('post', 'previous_post', 'next_post'));
    }
}
